//
//  YTPhotoLibraryController.m
//  YUNT
//
//  Created by haha on 2017/11/19.
//  Copyright © 2017年 梁炜东. All rights reserved.
//

#import "YTPhotoLibraryController.h"
#import "YTPhotoPreviewController.h"
#import "YTPhotoLibraryManager.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
#import "YTVideoPlayerController.h"

@interface YTDisplayHeader : UICollectionReusableView

@property (nonatomic, strong) UILabel *textLabel;

@end

@implementation YTDisplayHeader

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self)
    {
        self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 120, 20)];
        
        self.textLabel.textColor = [UIColor whiteColor];
        
        [self addSubview:self.textLabel];
    }
    
    return self;
}

@end

@interface YTPLDisplayCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) UIImageView *logoView;

@property (nonatomic, strong) UIButton *markBtn;

@property (nonatomic, strong) NSIndexPath *indexPath;

@property (nonatomic, assign) BOOL isSelect;

@property (nonatomic, assign) BOOL isReady;

@property (nonatomic, strong) YTPhotoLibraryItem *resourceItem;

@end

@implementation YTPLDisplayCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.userInteractionEnabled = YES;
        
        _indexPath = [[NSIndexPath alloc]init];

        _imageView = [[UIImageView alloc]initWithFrame:CGRectZero];
        
        _imageView.userInteractionEnabled = YES;
        
        _imageView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
        
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        _imageView.clipsToBounds = YES;
        
        [self.contentView addSubview:_imageView];
        
        _logoView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.size.width/2 - 20, self.bounds.size.height/2 - 20, 40, 40)];
        
        _logoView.userInteractionEnabled = YES;
        
        [self.contentView addSubview:_logoView];
        
        _logoView.image = nil;
        
        _markBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        _markBtn.frame = CGRectMake(_imageView.right - 5.0f - 20.0f, 5.0f, 20.0f, 20.0f);
        
        [_markBtn setContentMode:UIViewContentModeCenter];
        
        [_imageView addSubview:_markBtn];
        
        _isSelect = NO;
        
        _isReady = NO;
    }
    return self;
}

- (void)setIsReady:(BOOL)isReady
{
    _isReady = isReady;
    
    if (_isReady)
    {
        _markBtn.hidden = NO;
    }
    else
    {
        _markBtn.hidden = YES;
    }
    
    _isSelect = NO;
    
    [_markBtn setBackgroundImage:[UIImage imageNamed:@"rf_session_imagpicker_default"] forState:UIControlStateNormal];
}

- (void)setIsSelect:(BOOL)isSelect
{
    _isSelect = isSelect;
    
    if (_isReady)
    {
        if (self.isSelect)
        {
            [_markBtn setBackgroundImage:[UIImage imageNamed:@"rf_session_imagpicker_select"] forState:UIControlStateNormal];
        }
        else
        {
            [_markBtn setBackgroundImage:[UIImage imageNamed:@"rf_session_imagpicker_default"] forState:UIControlStateNormal];
        }
    }
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    
    if (_isReady)
    {
        if (self.isSelect)
        {
            [_markBtn setBackgroundImage:[UIImage imageNamed:@"rf_session_imagpicker_select"] forState:UIControlStateNormal];
        }
        else
        {
            [_markBtn setBackgroundImage:[UIImage imageNamed:@"rf_session_imagpicker_default"] forState:UIControlStateNormal];
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
}

- (void)setResourceItem:(YTPhotoLibraryItem *)resourceItem
{
    if (_resourceItem != resourceItem)
    {
        _resourceItem = resourceItem;
        
        if ([resourceItem.resourceType isEqualToString:@"jpeg"])
        {
            _imageView.image = [UIImage imageWithData:resourceItem.resourceData];
        }
        else
        {
            NSString *videoPath = [kVideoPath stringByAppendingString:resourceItem.resourceName];
            
            _imageView.image = [self thumbnailImageForVideo:[NSURL fileURLWithPath:videoPath] atTime:1];
        }
    }
    
    if ([_resourceItem.resourceType isEqualToString:@"MOV"] || [_resourceItem.resourceType isEqualToString:@"mp4"])
    {
        _logoView.image = [UIImage imageNamed:@"94"];
    }
    else
    {
        _logoView.image = nil;
    }
}

- (UIImage *)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
    
    return thumbnailImage;
}

- (void)dealloc
{
    _imageView = nil;
    
    _indexPath = nil;
}

@end

@interface YTPhotoLibraryController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *allCollectionView;

@property (nonatomic, strong) NSMutableArray *selectedResources;

@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation YTPhotoLibraryController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - init

- (void)initAttributes
{
    _isSelect = NO;
    
    _currentPage = 0;
    
    _allKeys = [NSArray array];
    
    _selectedResources = [NSMutableArray array];
}

- (void)initSubViews
{
    [self initCollectionView];
}

- (void)initCollectionView
{
    UICollectionViewFlowLayout *allFlowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    allFlowLayout.itemSize = CGSizeMake((self.view.width - 20.0f)/4.0f, (self.view.width - 20.0f)/4.0f);
    
    allFlowLayout.minimumInteritemSpacing = 4.0f;
    
    allFlowLayout.minimumLineSpacing = 4.0f ;
    
    allFlowLayout.sectionInset = UIEdgeInsetsMake(4.0f, 4.0f, 0, 4.0f);
    
    allFlowLayout.headerReferenceSize = CGSizeMake(self.view.width, 40.0f);
    
    _allCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, self.view.width, self.view.height)collectionViewLayout:allFlowLayout];
    
    _allCollectionView.userInteractionEnabled = YES;
    
    _allCollectionView.backgroundColor = [UIColor blackColor];
    
    _allCollectionView.bounces = NO;
    
    _allCollectionView.delegate = self;
    
    _allCollectionView.dataSource = self;
    
    _allCollectionView.scrollsToTop = NO;
    
    [_allCollectionView registerClass:[YTPLDisplayCell class] forCellWithReuseIdentifier:@"YTPLDisplayCellId"];
    
    [_allCollectionView registerClass:[YTDisplayHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YTDisplayHeaderID"];
    
    [self.view addSubview:_allCollectionView];
}

#pragma mark -UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.allKeys.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSString *key = self.allKeys[section];
    
    NSArray *arr = self.resources[key];
    
    return arr.count;
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        YTDisplayHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YTDisplayHeaderID" forIndexPath:indexPath];
        
        NSString *key = self.allKeys[indexPath.section];
        
        headerView.textLabel.text = key;
        
        reusableview = headerView;
    }

    reusableview.backgroundColor = [UIColor blackColor];
    
    return reusableview;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YTPLDisplayCell *cell = nil;
    
    cell.userInteractionEnabled = YES;
    
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YTPLDisplayCellId" forIndexPath:indexPath];
    
    cell.isReady = _isSelect;
    
    cell.indexPath = indexPath;
    
    NSString *key = key = self.allKeys[indexPath.section];
    
    cell.resourceItem = self.resources[key][indexPath.row];
    
    if ([[YTPhotoLibraryManager defaultManager].selectedResources containsObject:cell.resourceItem])
    {
        cell.isSelect = YES;
    }
    else
    {
        cell.isSelect = NO;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isSelect)
    {
        YTPLDisplayCell *cell = (YTPLDisplayCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        cell.isSelect = !cell.isSelect;
        
        YTPhotoLibraryItem *resourceItem = cell.resourceItem;
        
        if ([[YTPhotoLibraryManager defaultManager].selectedResources containsObject:resourceItem])
        {
            [[YTPhotoLibraryManager defaultManager].selectedResources removeObject:resourceItem];
        }
        else
        {
            [[YTPhotoLibraryManager defaultManager].selectedResources addObject:resourceItem];
        }
        
        if ([YTPhotoLibraryManager defaultManager].selectedResources .count > 0)
        {
            self.parentViewController.navigationItem.leftBarButtonItem.enabled = YES;
        }
        else
        {
            self.parentViewController.navigationItem.leftBarButtonItem.enabled = NO;
        }
    }
    else
    {
        YTPLDisplayCell *cell = (YTPLDisplayCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        YTPhotoLibraryItem *resourceItem = cell.resourceItem;
        
        if ([resourceItem.resourceType isEqualToString:@"MOV"] || [resourceItem.resourceType isEqualToString:@"mp4"])
        {
            YTVideoPlayerController *playVC = [[YTVideoPlayerController alloc] init];
            
            playVC.resoucesItem = resourceItem;
            
            [self.navigationController pushViewController:playVC animated:YES];
        }
        else if ([resourceItem.resourceType isEqualToString:@"jpeg"] || [resourceItem.resourceType isEqualToString:@"png"])
        {
            NSMutableArray *arr = [NSMutableArray array];
            
            [arr indexOfObject:cell.resourceItem];
            
            YTPhotoPreviewController *previewVC = [[YTPhotoPreviewController alloc] init];
            
            NSArray *array = [[YTPhotoLibraryManager defaultManager] readAllImagesArray];
            
            previewVC.imageArray = array;
            
            previewVC.initialPositon = [NSIndexPath indexPathForRow:[array indexOfObject:cell.resourceItem] inSection:0];
            
            [self.navigationController pushViewController:previewVC animated:YES];
        }
    }
}

#pragma buttonresponder

- (void)updateSelectStatus:(BOOL)status
{
    self.isSelect = status;
    
    [self.allCollectionView reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
